package xcity

import (
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 获取市区列表信息
//
//	province_code	省/直辖市code
func CityList(province_code uint) ([]City, error) {
	if province_code%10000 != 0 {
		return nil, xerror.New("传入的省份code不正确")
	}
	cache_key := xcache.Key("xcity.city_list", province_code)
	cit := []City{}
	if xcache.Exists(cache_key) {
		if err := xcache.GetStruct(cache_key, &cit); err == nil {
			return cit, nil
		}
		cit = []City{}
	}
	if _default.DB == nil {
		return nil, xerror.New("数据库未连接")
	}
	// 从数据库中进行读取
	err := _default.DB.Table(_default.CityName).
		Where("ad_code > ? and ad_code < ?", province_code, province_code+10000).
		Where("ad_code % 100 = 0").
		Order("ad_code ASC").
		Find(&cit).
		Error
	if err != nil {
		return nil, err
	}
	xcache.SetStruct(cache_key, cit)
	return cit, nil
}
